// CatalogCon
package control

import (
	"database/sql"
	"strconv"

	"crossrun.top/model"
)

//列出文章类型
func ListCataLog() ([]model.Catalog, error) {
	rows, err := db.Query("SELECT * FROM catalog")
	defer rows.Close()
	return processCatalog(rows), err
}

//通过id列出文章类型
func FindCataLogById(id string) []model.Catalog {
	//查询数据
	rows, err := db.Query("SELECT * FROM catalog where id = ?", id)
	defer rows.Close()
	checkErr(err)
	return processCatalog(rows)
}

//新增一个文章分类
func AddCatalog(name string, typei int) (model.Catalog, error) {
	var cat model.Catalog
	s := "INSERT INTO catalog(name, typei) values(?,?)"
	//插入数据
	stmt, err := db.Prepare(s)
	if err != nil {
		return cat, err
	}
	res, err := stmt.Exec(name, typei)
	if err != nil {
		return cat, err
	}
	id, err := res.LastInsertId()
	if err != nil {
		return cat, err
	}
	cat.Name = name
	cat.Id = strconv.FormatInt(id, 10)
	cat.Type = typei
	return cat, err
}

func processCatalog(rows *sql.Rows) []model.Catalog {
	var catas []model.Catalog
	for rows.Next() {
		var name string
		var id string
		var typei int
		err := rows.Scan(&name, &id, &typei)
		checkErr(err)
		catas = append(catas, model.Catalog{name, id, typei})
	}
	return catas
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
